<template>
  <div class="addDialg">
    <el-dialog
      :close-on-click-modal="false"
      :title="titleName"
      :visible.sync="dialogTableVisible"
      width="80%">

      <div class="pageTop">
        <el-form :rules="rules" :model="addDialgData" ref="addDialgData" :inline="true" class="inputWidth"  style="padding: 0px 10px; padding-top: 20px;" >
          <el-form-item label="采购计划" prop="purchasePlanNo">
            <el-input show-overflow-tooltip  size="medium" disabled placeholder="请选择采购计划" v-model="addDialgData.purchasePlanNo" class="input-with-select">
              <el-button @click="handleIconClickDh" slot="append" icon="el-icon-more"></el-button>
            </el-input>
          </el-form-item>

          <el-form-item label="校正仓库:" v-show="addDialgData.warehouseId">
            <span>{{addDialgData.warehouseId}}</span>
            <span>{{addDialgData.warehouseName}}</span>
          </el-form-item>
          <el-form-item label="单据日期"  label-width="100px" prop="crtTime">
            <el-date-picker
              v-model="addDialgData.crtTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="单据编号：" label-width="100px">
            <span> {{addDialgData.correctionCode}}</span>
          </el-form-item>
          <el-form-item label="备注：" label-width="100px">
            <el-input
              maxlength="250" show-word-limit
              v-model="addDialgData.remark"
              placeholder="请输入备注"
              clearable
              size="medium"
            />
          </el-form-item>
        </el-form>
      </div>
      <el-table  height="350" v-loading="loading" :data="addDialgData.manualCorrectionInfoAddDTOS" stripe border style="margin-top: 20px" :header-cell-style="{background:'#eef1f6',color:'#606266'}">
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column align="center" label="商品"   property="goodsName" width="200" show-overflow-tooltip> </el-table-column>
        <el-table-column align="center" label="商品编号"   property="goodsId"></el-table-column>
        <el-table-column align="center" label="商品编码"   property="goodsSn"></el-table-column>
        <el-table-column align="center" label="库存"   property="inventory" width="80"></el-table-column>
        <el-table-column align="center" label="单位"   property="goodsUnit"></el-table-column>
        <el-table-column align="center" label="计划采购数"   property="planCount" width="100"> </el-table-column>
        <el-table-column align="center" label="实际到货数"   property="atPresentCount" width="100">
          <template slot-scope="scope">
            <el-input onkeyup="value=value.replace(/[^\d]+/g,'')"  v-show="scope.row.goodsId" v-model="scope.row.atPresentCount" type="text" placeholder=""></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="校正数量"   property="">
          <template slot-scope="scope">
           <span  v-show="scope.row.atPresentCount && scope.row.planCount">{{  scope.row.atPresentCount*1-scope.row.planCount*1}}</span>
          </template>
        </el-table-column>
        <el-table-column  align="center" label="校正金额"   property="">
          <template slot-scope="scope">
            <span  v-show="scope.row.atPresentCount && scope.row.planCount">{{Math.round ((scope.row.atPresentCount*1-scope.row.planCount*1)* scope.row.marketPrice)/ 100  }}</span>
          </template>

        </el-table-column>

        <el-table-column align="center" label="采购单价"   property="marketPrice"></el-table-column>
        <el-table-column align="center" label="图片（原因说明）"   property="url" width="150">
          <template slot-scope="scope">
            <el-upload
              class="upload-demo"
              :headers="myHeaders"
              Method="post"
              v-show="scope.row.goodsId && !scope.row.picUrl"
              :action="baseURL+'/oss/uploads'"
              :on-success="fileSuccess"
              :on-error="uploadFileError"
              :show-file-list="false"
              :limit="10">
              <el-button size="small" type="primary" @click="shaungchuan(scope.$index)">点击上传</el-button>
            </el-upload>
            <el-popover placement="top-start" title="" trigger="hover" v-show="scope.row.goodsId && scope.row.picUrl">
              <img :src="scope.row.picUrl" alt="" style="width: 200px;height: 200px">
              <img slot="reference" :src="scope.row.picUrl" style="width:50px;height: 50px">
            </el-popover>
            <i @click="shanchua(scope.$index)" v-show="scope.row.goodsId && scope.row.picUrl" class="el-icon-delete" style="position: absolute;top: 0px;right: 47px;color: red;cursor: pointer"></i>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注"   property="note" width="200">
          <template slot-scope="scope">
            <el-input maxlength="250" show-word-limit v-show="scope.row.goodsId" v-model="scope.row.remark"  placeholder="这里写备注"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <div class="pageTop">
        <el-form :model="addDialgData" ref="addDialgData" :inline="true" class="inputWidth"  style="padding: 0px 10px; padding-top: 20px;" label-width="100px" >
          <el-form-item label="校正人：">
            {{yunyingName}}
          </el-form-item>
          <el-form-item label="下单时间：" v-show="addData.leixing=='put'">
            {{addDialgData.crtTime}}
          </el-form-item>
          <el-form-item label="审核人：" v-show="addData.leixing=='put'">
            {{addDialgData.auditUserName}}
          </el-form-item>
          <el-form-item label="审核时间：" v-show="addData.leixing=='put'">
            {{addDialgData.checkDate}}
          </el-form-item>
          <el-form-item label="审核状态：" v-show="addData.leixing=='put'">
            <span v-show="zhuangtai==2" style="color: red">未审核</span>
            <span v-show="zhuangtai==3" style="color: red">已审核</span>
            <span v-show="zhuangtai==4" style="color: red">驳回</span>
          </el-form-item>
          <el-form-item label="" style="float: right">
            <el-button v-if="auditQX==1"  type="primary" size="medium" @click="shBtn" v-show="addData.leixing=='put' && zhuangtai==2 ||zhuangtai==4 " >审核</el-button>
            <el-button v-if="auditQX==1"  type="primary" size="medium" @click="fsBtn" v-show="addData.leixing=='put' && zhuangtai==3 ">反审</el-button>
            <el-button  :loading="loading"  v-if="addQX==1" type="success"  size="medium" @click="saveBtn" v-show="addData.leixing=='post' || zhuangtai==2 ||zhuangtai==4">保存</el-button>
<!--            <el-button type="danger" size="medium" @click="delBtn" >删除</el-button>-->
          </el-form-item>
        </el-form>
      </div>

    </el-dialog>
    <shangpin-Dialog v-if="shangpinShow" :shnagpinData="shnagpinData" @callback="callback"></shangpin-Dialog>
    <cgd-Dialog v-if="cgdShow" :shnagpinData="cgdData" @callback="cgdback"></cgd-Dialog>
    <cgjh-Dialog v-if="cgjhShow" :cgdData="cgjhData" @callback="cgjhback"></cgjh-Dialog>

  </div>
</template>

<script>
import request from '@/utils/request'
import shangpinDialog from '../../components/shangpinDialog'
import cgdDialog from '../../components/cgdDialog'
import {DeleteJL,focusXL,selectCG,getnewDat} from "@/utils/index"
import cgjhDialog from '../../components/cgjhDialog'
export default {
  props: ['addData'],
  name: "Role",
  components:{
    shangpinDialog,
    cgdDialog,
    cgjhDialog
  },
  data() {
    return {
      cgjhData:{},
      cgjhShow:false,
      deleteQX:localStorage.getItem("delete"),//删除权限
      addQX:localStorage.getItem("add"),//保存权限
      auditQX:localStorage.getItem("audit"),//审核权限
      yunyingName:localStorage.getItem("loginUserName"),
      imgList:[],
      zhuangtai:2,
      uploadData: {
        file_key: 'file',
        business_id: '',
      },
      myHeaders: {Authorization:'Bearer ' + localStorage.getItem('token')},
      indexDl:0,
      // 表单校验
      rules: {
        purchasePlanNo: [
          { required: true, message: "采购计划不能为空", trigger: "blur" }
        ],
        crtTime: [
          { required: true, message: "单据日期不能为空", trigger: "blur" }
        ],

      },
      states: '未校正',
      cgdShow: false,
      cgdData: {},
      rkckName: '未选择',
      shnagpinData: {},
      shangpinShow: false,
      xiabiao: 0,
      //商品输入下拉
      restaurants: [],
      leixing: 'post',
      titleName: '新增人工校正单',
      loading: false,
      //记录数据
      modifyData:{
        correctionCode:'',
        manualCorrectionInfoAddDTOS:[],
      },
      //单据日期
      djDateList: [],
      dialogTableVisible: true,

      //新增的参数列表
      addDialgData: {
        purchasePlanNo:'',
        correctionCode: '',
        crtTime: '',
        warehouseId: '',
        warehouseName: '',
        remark:'',
        manualCorrectionInfoAddDTOS:[],
      },
      baseURL:localStorage.getItem('baseURL')
    }
  },
  watch: {
    dialogTableVisible: function () {
      this.dialogTableVisible = true;//始终让他为true;
      this.cancel();//隐藏
    },
  },
  created() {
    // var baseURL = localStorage.getItem('baseURL')
    // console.log('baseURL',baseURL)

    this.zhuangtai = this.addData.purchasePlanStatus
    this.addDialgData.correctionCode ='RGXZ'+Date.parse(new Date())/1000;
    var arr =  getnewDat()
    this.addDialgData.crtTime = arr[0]
    this.getshangpin();
    console.log('接受',this.addData)
    if(this.addData.leixing=='put'){
      this.titleName = '修改人工校正单'

      this.gethuixian()
    }
  },
  mounted() {

  },
  methods: {
    //采购计划回调
    cgjhback:function (msg){
      this.cgjhShow = false
      if(!msg){
        return
      }
      this.addDialgData.purchasePlanId = msg.radioId
      this.addDialgData.purchasePlanNo=msg.purchasePlanNo
      this.addDialgData.purchasePlanName = msg.ckname
      console.log('msg',msg)
      if(msg.radioId){
        this.gethdSP(msg.radioId)
      }

    },
    //获取回调函数商品
    gethdSP:function (id){
      this.loading = true
      request({
        url: '/wh/purchasePlan/getVoById/'+id,
        method: 'get',
      }).then(response => {
        this.loading = false
        if(response.code=='200'){
          this.addDialgData.purchasePlanNo=response.data.purchasePlanNo
          this.addDialgData.manualCorrectionInfoAddDTOS = response.data.purchasePlanInfoVOList
          for(var i=0;i<this.addDialgData.manualCorrectionInfoAddDTOS.length;i++){
            this.addDialgData.manualCorrectionInfoAddDTOS[i].planCount = this.addDialgData.manualCorrectionInfoAddDTOS[i].purchasePlanNumber
          }
          this.addDialgData.warehouseName = response.data.warehouseName
          this.addDialgData.warehouseId = response.data.warehouseId
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }

      });

    },
    //采购单号点击
    handleIconClickDh(ev) {
      console.log('点击',ev);
      var obj={}
      obj.isEmploy= 2
      obj.isManul='1'
      obj.supplierId = this.addDialgData.supplierId //供应商
      obj.warehouseId = this.addDialgData.warehouseId //仓库
      console.log('传参数',obj.isEmploy);
      this.cgjhData = obj
      this.cgjhShow = true
    },
    //校正仓库校验
    cangkChange:function (){
      this.addDialgData.manualCorrectionInfoAddDTOS=[]
      this.addDialgData.manualCorrectionInfoAddDTOS.push(
        { goodsId:'',goodsName:'', goodsUnit:'',correctionNum:'1',correctionPrice:'',remark:'',url:''},
      )
    },
    //删除
    shanchua:function (index){
      console.log(index)
      this.addDialgData.manualCorrectionInfoAddDTOS[index].picUrl = ''
    },
    //获取下拉焦点
    focusBtn:function (index,row){
      focusXL(index)
    },
    //获取回显数据
    gethuixian:function () {
      this.loading = true
      request({
        url: '/wh/manualCorrection/getById/' + this.addData.id,
        method: 'get',
      }).then(response => {

        this.loading = false
        if(response.code==200){
          this.addDialgData = response.data
          console.log('houtai',this.addDialgData.manualCorrectionInfoAddDTOS )
          this.jisuanshuliang(this.addDialgData.manualCorrectionInfoAddDTOS)
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }

      });
    },
    //数量监听
    changeSL:function (){
      console.log('监听',this.addDialgData.manualCorrectionInfoAddDTOS)
      this.jisuanshuliang(this.addDialgData.manualCorrectionInfoAddDTOS)
    },
    //获取所有商品
    getshangpin:function (){
      var obj={}
      obj.current = 1
      obj.size= 10000
      request({
        url: '/wh/products/page',
        method: 'get',
        params:obj
      }).then(response => {
        this.restaurants = response.data.records
        for (var i=0;i<this.restaurants.length;i++){
          this.restaurants[i].value =  this.restaurants[i].barCode
        }
      });
    },
    //点击上传
    shaungchuan:function (index){
      this.indexDl = index
      console.log('this.indexDl',this.indexDl)

    },
    // 上传成功
    fileSuccess(res) {
      if(res.code==200){
        //文件上传成功
        this.$message({
          type: 'success',
          message: '上传成功'
        });
      }else {
        this.$message({
          type: 'error',
          message: res.msg
        });
      }
      var obj=''
      obj = res.data[0].url

      this.addDialgData.manualCorrectionInfoAddDTOS[this.indexDl].picUrl=obj
      this.imgList.push({
        picUrl:res.data[0].picUrl
      })
      console.log('this.imgList',this.imgList)

    },
    uploadFileError(err, file, fileList) {
      //文件上传成功
      this.$message({
        type: 'error',
        message: '上传失败'
      });
    },
    //添加
    addBtn:function (){
      this.addDialgData.manualCorrectionInfoAddDTOS.push(
        { goodsId:'',goodsName:'', goodsUnit:'',correctionNum:'1',correctionPrice:'',remark:'',picUrl:''},
      )
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      selectCG(item,this.addDialgData.manualCorrectionInfoAddDTOS,this)
      this.jisuanshuliang(this.addDialgData.manualCorrectionInfoAddDTOS)
    },
    //计算页面数据
    jisuanshuliang:function (ymArr){
      for (var i=0;i<ymArr.length;i++){
        var sum=0;
        console.log(ymArr[i].price)

        if(ymArr[i].price==null||ymArr[i].price==''){
          // correctionPrice=ymArr[i].correctionPrice;
        }else{
          sum=Math.round ((ymArr[i].correctionNum*1)*(ymArr[i].price*1)*100) / 100;
        }
        ymArr[i].correctionPrice=sum;
      }
    },
    handleSelectDh(item) {
      console.log('选择单号',item);
      this.rkckName= item.name

    },
    handleIconClick(ev) {
      console.log('点击',ev);
      if(!this.addDialgData.warehouseId){
        this.$message({
          type: 'warning',
          message:'请选择校正仓库！'
        });
        return
      }

      var obj={}
      obj.warehouseId =this.addDialgData.warehouseId
      this.shnagpinData = obj
      this.shangpinShow = true
    },
    //采购单 弹框回调
    cgdback:function (item){
      this.cgdShow = false
      this.addDialgData.danhao = item.radioId
      this.rkckName = item.ckname
      console.log('采购单',item);
    },
    //弹框回调
    callback:function (item){
      this.shangpinShow = false
      if(!item){
        return

      }
      console.log('item',item)
      this.shangpinShow = false
      this.addDialgData.manualCorrectionInfoAddDTOS = this.addDialgData.manualCorrectionInfoAddDTOS.concat(item)
      for(var i=0;i<this.addDialgData.manualCorrectionInfoAddDTOS.length;i++){
        if( this.addDialgData.manualCorrectionInfoAddDTOS[i].goodsId==''){//解决初始化id为空导致多一条空数据
          this.addDialgData.manualCorrectionInfoAddDTOS.splice(i,1);
          this.addDialgData.manualCorrectionInfoAddDTOS[i].picUrl=''
        }
      }
      console.log('商品',this.addDialgData.manualCorrectionInfoAddDTOS)

    },
    //删除采购单
    delBtn:function (){
      this.$confirm('此操作将删除采购单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //保存
    saveBtn:function (){
      if(!this.addDialgData.crtTime){
        this.$message({
          type: 'warning',
          message:'单据日期不能为空！'
        });
        return
      }
      if(!this.addDialgData.purchasePlanNo){
        this.$message({
          type: 'warning',
          message:'请选择采购计划！'
        });
        return
      }
      for(var i=0;i<this.addDialgData.manualCorrectionInfoAddDTOS.length;i++){
        if(!this.addDialgData.manualCorrectionInfoAddDTOS[i].atPresentCount){
          this.$message({
            type: 'warning',
            message:'有商品未选择实际到货数，请填写！'
          });
          return
        }
        this.addDialgData.manualCorrectionInfoAddDTOS[i].correctionNum = this.addDialgData.manualCorrectionInfoAddDTOS[i].atPresentCount*1-this.addDialgData.manualCorrectionInfoAddDTOS[i].planCount*1
        this.addDialgData.manualCorrectionInfoAddDTOS[i].correctionPrice = Math.round ((this.addDialgData.manualCorrectionInfoAddDTOS[i].atPresentCount*1-this.addDialgData.manualCorrectionInfoAddDTOS[i].planCount*1)* this.addDialgData.manualCorrectionInfoAddDTOS[i].marketPrice)/ 100
      }
      this.loading=true


      if(this.addData.leixing=='put'){//修改
        request({
          url: '/wh/manualCorrection/update',
          method: 'PUT',
          data:this.addDialgData
        }).then(response => {
          this.loading=false
          this.cancel();//隐藏
          if(response.code=='200'){
            this.$message({
              type: 'success',
              message:response.msg
            });
          }else {
            this.$message({
              type: 'warning',
              message:response.msg
            });
          }

        });
        return
      }
      //新增
      request({
        url: '/wh/manualCorrection/add',
        method: 'post',
        data:this.addDialgData
      }).then(response => {
        this.cancel();//隐藏
        this.loading=false
        if(response.code=='200'){
          this.$message({
            type: 'success',
            message:response.msg
          });
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }

      });


    },
    //审核
    shBtn:function (){
      this.$confirm('此操作将审核通过, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.shenhe();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消审核'
        });
      });
    },
    //审核
    shenhe:function (){
      request({
        url: '/wh/manualCorrection/audit?id='+this.addData.id,
        method: 'put',
      }).then(response => {
        if(response.code==200){
          this.$message({
            type: 'success',
            message:response.msg
          });
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }
        this.cancel();//隐藏
      });
    },
    //反审
    fsBtn:function (){
      this.$confirm('此操作将反审, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.bohui();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消反审'
        });
      });
    },
    //驳回
    bohui:function (){
      request({
        url: '/wh/manualCorrection/rejected?id='+this.addData.id,
        method: 'put',
      }).then(response => {
        if(response.code==200){
          this.$message({
            type: 'success',
            message:response.msg
          });
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }
        this.cancel();//隐藏
      });
    },
    //删除
    handleDelete:function (index,row){
      DeleteJL(index,row,this.addDialgData.manualCorrectionInfoAddDTOS,this.modifyData.manualCorrectionInfoAddDTOS)
    },
    //确定
    determine:function(){

      this.$emit('callback','参书')//将submitModel的值传给父组件
    },
    //隐藏
    cancel:function(){
      // this.determine()
      this.$emit('callback','')//将submitModel的值传给父组件
    },

  }
};
</script>
<style scoped>
.addDialg {

}


</style>
